<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>文档标题</title>
</head>

<body>
webtransport demo
<input type="button" id="connect" value="Connect" onclick="connect()">
</body>

<script type="text/javascript">
    let transport, streamNumber
    streamNumber = 1
    async function heartbeat() {
        console.log('------')
        let stream = await transport.createBidirectionalStream();
        let writer = stream.writable.getWriter();
        let encoder = new TextEncoder('utf-8');
        let data = encoder.encode("ping");
        await writer.write(data);
        await writer.close();
    }

    async function connect() {

        const url = 'https://barrage.houry.top/test';

        transport = new WebTransport(url);
        console.log("---success----")
        transport.closed.then(() => {
            console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
        }).catch((error) => {
            console.error('The HTTP/3 connection to ${url} closed due to ${error}.');
        });
        await transport.ready;

        setInterval(() => {
            heartbeat()
        }, 2 * 1000)

        acceptUnidirectionalStreams(transport)

    }

    async function acceptUnidirectionalStreams(transport) {
        console.log("---acceptUnidirectionalStreams----")
        let reader = transport.incomingUnidirectionalStreams.getReader();
        try {
            while (true) {
                const { value, done } = await reader.read();
                if (done) {
                    console.log('Done accepting unidirectional streams!');
                    return;
                }
                let stream = value;
                let number = streamNumber++;
                console.log('New incoming unidirectional stream #' + number);
                readFromIncomingStream(stream, number);
            }
        } catch (e) {
            console.log('Error while accepting streams: ' + e, 'error');
        }
    }


    async function readFromIncomingStream(readable, number) {
        const decoder = new TextDecoderStream('utf-8');
        let reader = readable.pipeThrough(decoder).getReader();
        try {
            while (true) {
                const { value, done } = await reader.read();
                if (done) {
                    console.log('Stream #' + number + ' closed');
                    return;
                }
                let data = value;
                console.log('Received data on stream #' + number + ': ' + data);
            }
        } catch (e) {
            console.log(
                'Error while reading from stream #' + number + ': ' + e, ' error');
            console.log('    ' + e.message);
        }
    }
</script>

</html>
